#!/usr/bin/env python
# -*- coding:utf-8 -*-

from controller.planController import PlanController

import datetime
import math

from flask import current_app ,make_response ,jsonify,g
from sqlalchemy import or_
from werkzeug.security import generate_password_hash, check_password_hash

from app import db
from models.plan import Plan
from models.user import User
from models.dictionary import Dictionary
from utils import commons
from utils.generate_id import GenerateID
from utils.loggings import loggings
from utils.response_code import RET, error_map_EN
from utils.rsa_encryption_decryption import RSAEncryptionDecryption

class PlanService(PlanController):

    # 保存学习计划
    @classmethod
    def save_plan(cls, **kwargs):
        try:
            # 参数校验
            required_params = ['dictionary_id', 'plan_type', 'user_id']
            missing_params = [param for param in required_params if param not in kwargs]
            if missing_params:
                return {'code': RET.PARAMERR, 'message': f'参数不完整: {", ".join(missing_params)}', 'data': None}

            # 检查 plan_quantity 和 plan_time 是否同时存在
            if 'plan_quantity' in kwargs and 'plan_time' in kwargs:
                return {'code': RET.PARAMERR, 'message': '只能提供 plan_quantity 或 plan_time 中的一个', 'data': None}

            # 检查 plan_quantity 或 plan_time 是否至少存在一个
            if 'plan_quantity' not in kwargs and 'plan_time' not in kwargs:
                return {'code': RET.PARAMERR, 'message': '必须提供 plan_quantity 或 plan_time 中的一个', 'data': None}

            # 检查用户是否存在
            user = db.session.query(User).filter(
                User.user_id == kwargs['user_id'],
                User.is_delete == 0
            ).first()

            if not user:
                return {'code': RET.DBERR, 'message': '用户不存在', 'data': None}

            # 检查词典是否存在
            dictionary = db.session.query(Dictionary).filter(
                Dictionary.dictionary_id == kwargs['dictionary_id'],
                Dictionary.is_delete == 0
            ).first()

            if not dictionary:
                return {'code': RET.DBERR, 'message': '词典不存在', 'data': None}

            # 检查是否已经存在相同用户和词典的学习计划
            existing_plan = db.session.query(Plan).filter(
                Plan.user_id == kwargs['user_id'],
                Plan.dictionary_id == kwargs['dictionary_id'],
                Plan.is_delete == 0
            ).first()

            if existing_plan:
                # 更新现有的学习计划
                existing_plan.plan_quantity = kwargs.get('plan_quantity')
                existing_plan.plan_time = kwargs.get('plan_time')
                existing_plan.plan_type = kwargs['plan_type']
                existing_plan.update_time = datetime.datetime.now()
            else:
                # 生成唯一的 plan_id
                plan_id = GenerateID.create_random_id()

                # 创建新的学习计划对象
                new_plan = Plan(
                    plan_id=plan_id,
                    plan_quantity=kwargs.get('plan_quantity'),
                    plan_time=kwargs.get('plan_time'),
                    dictionary_id=kwargs['dictionary_id'],
                    plan_type=kwargs['plan_type'],
                    user_id=kwargs['user_id'],
                    is_delete=0,  # 默认不删除
                    create_time=datetime.datetime.now(),
                    update_time=datetime.datetime.now()
                )

                # 添加到数据库会话
                db.session.add(new_plan)

            # 提交数据库会话
            db.session.commit()

            # 返回成功响应
            return {'code': RET.OK, 'message': 'Plan saved successfully',
                    'data': existing_plan.plan_id if existing_plan else new_plan.plan_id}

        except Exception as e:
            # 回滚事务
            db.session.rollback()
            # 记录错误日志
            loggings.exception(1, e)
            # 返回错误响应
            return {'code': RET.DBERR, 'message': 'Database error', 'data': None}

    # 逻辑删除学习计划
    @classmethod
    def delete_plan(cls, params):
        try:
            # 从字典中提取 user_id 和 dictionary_id
            user_id = params.get('user_id')
            dictionary_id = params.get('dictionary_id')

            if not user_id or not dictionary_id:
                return {'code': RET.PARAMERR, 'message': '参数缺失', 'data': None}

            # 检查用户是否存在
            user = db.session.query(User).filter(
                User.user_id == user_id,
                User.is_delete == 0
            ).first()

            if not user:
                return {'code': RET.DBERR, 'message': '用户不存在', 'data': None}

            # 检查词典是否存在
            dictionary = db.session.query(Dictionary).filter(
                Dictionary.dictionary_id == dictionary_id,
                Dictionary.is_delete == 0
            ).first()

            if not dictionary:
                return {'code': RET.DBERR, 'message': '词典不存在', 'data': None}

            # 检查是否存在相同用户和词典的学习计划
            existing_plan = db.session.query(Plan).filter(
                Plan.user_id == user_id,
                Plan.dictionary_id == dictionary_id,
                Plan.is_delete == 0
            ).first()

            if not existing_plan:
                return {'code': RET.DBERR, 'message': '学习计划不存在', 'data': None}

            # 逻辑删除学习计划
            existing_plan.is_delete = 1
            existing_plan.update_time = datetime.datetime.now()

            # 提交数据库会话
            db.session.commit()

            # 返回成功响应
            return {'code': RET.OK, 'message': '学习计划已删除', 'data': None}

        except Exception as e:
            # 回滚事务
            db.session.rollback()
            # 记录错误日志
            loggings.exception(1, e)
            # 返回错误响应
            return {'code': RET.DBERR, 'message': 'Database error', 'data': None}

